# -*- coding: utf-8 -*-
"""
| @brief 学习sorted
| @author Wuming
| @date 2022-04-12 23:20:34
| @version 1.0.0
"""
from datetime import datetime
import unittest
from functools import cmp_to_key
from typing import Union


class Position:
    """坐标"""

    def __init__(self, x: Union[int, float], y: Union[int, float]):
        self.x = x
        self.y = y

    def __lt__(self, other):
        """当在两个对象之间进行比较时，python排序使用 __lt__()。因此通过定义 __lt__()方法可以为类添加一个标准排序"""
        return self.distance() < other.distance()

    def __eq__(self, other):
        return isinstance(other, Position) and self.x == other.x and self.y == other.y

    def __repr__(self):
        return f'{self.__class__.__name__}({self.x},{self.y})'

    def distance(self) -> Union[int, float]:
        """返回几何距离的平方"""
        return self.x ** 2 + self.y ** 2


class SortedTestCase(unittest.TestCase):
    def test_key_kwargs(self):
        def compare_two_position(pos1: Position, pos2: Position) -> int:
            """Python 2.x 支持的 cmp 参数来处理用户指定的比较函数"""
            return int((pos1.distance() - pos2.distance()) * (10 ** 5))

        data1 = [Position(1, 2), Position(1, 1), Position(-1, 1), Position(3, 4), Position(3, 2)]
        data1_sort = [Position(1, 1), Position(-1, 1), Position(1, 2), Position(3, 2), Position(3, 4)]
        # 利用类中的__lt__()方法
        self.assertListEqual(data1_sort, sorted(data1))
        # 利用指定的键函数
        self.assertListEqual(data1_sort, sorted(data1, key=lambda x: x.distance()))
        # 利用指定的比较函数（Python 2.x 的cmp参数）
        self.assertListEqual(data1_sort, sorted(data1, key=cmp_to_key(compare_two_position)))


if __name__ == '__main__':
    start_time = datetime.now()
    print("[%s]%s开始运行..." % (start_time.strftime('%Y-%m-%d %H:%M:%S.%f'), __file__))

    unittest.main()

    end_time = datetime.now()
    print(f"[{end_time.strftime('%Y-%m-%d %H:%M:%S.%f')}]{__file__}结束运行.")
    print(f"耗时:{end_time - start_time}")
